<template>
	<div class="delivery-form-container">
		<div class="form-header">
			<div class="title-box">
				<div class="title">订单发货</div>
				<div class="order-no">订单号: {{ orderNo }}</div>
			</div>
			<u-icon name="close" size="24" color="#999" @click="$emit('cancel')" class="close-icon"></u-icon>
		</div>

		<div class="form-content">
			<u-form :model="form" ref="formRef" label-position="top">
				<!-- 发货方式选择 -->
				<u-form-item label="发货方式" prop="deliveryType" required>
					<div class="delivery-type-container">
						<div class="delivery-type-option" :class="{ active: form.deliveryType === 1 }" @click="form.deliveryType = 1">
							<div class="option-icon">
								<u-icon
									:name="form.deliveryType === 1 ? 'checkbox-mark' : 'circle'"
									size="20"
									:color="form.deliveryType === 1 ? '#2979ff' : '#c0c4cc'"
								></u-icon>
							</div>
							<div class="option-text">快递物流</div>
						</div>
						<div class="delivery-type-option" :class="{ active: form.deliveryType === 0 }" @click="form.deliveryType = 0">
							<div class="option-icon">
								<u-icon
									:name="form.deliveryType === 0 ? 'checkbox-mark' : 'circle'"
									size="20"
									:color="form.deliveryType === 0 ? '#2979ff' : '#c0c4cc'"
								></u-icon>
							</div>
							<div class="option-text">无需发货</div>
						</div>
					</div>
				</u-form-item>

				<!-- 物流公司选择 - 只在快递物流时显示 -->
				<u-form-item v-if="form.deliveryType === 1" label="物流公司" prop="logisticsId" required>
					<div class="select-wrapper" @click="showSelect = true">
						<u-input
							v-model="selectedLogisticsName"
							placeholder="请选择物流公司"
							disabled
							disabledColor="#fff"
							border="bottom"
							inputAlign="right"
							:customStyle="{ padding: '12px 0' }"
						>
							<template #suffix>
								<u-icon name="arrow-right" size="18" color="#c0c4cc"></u-icon>
							</template>
						</u-input>
					</div>
					<div v-if="logisticsError" class="error-tip">{{ logisticsError }}</div>
				</u-form-item>

				<!-- 物流单号输入 - 只在快递物流时显示 -->
				<u-form-item v-if="form.deliveryType === 1" label="物流单号" prop="logisticsNo" required>
					<u-input
						v-model="form.logisticsNo"
						placeholder="请输入物流单号"
						clearable
						border="bottom"
						inputAlign="right"
						:customStyle="{ padding: '12px 0' }"
					></u-input>
				</u-form-item>
			</u-form>
		</div>

		<!-- 物流公司选择弹窗 - 修复点击问题 -->
		<u-popup
			:show="showSelect"
			mode="bottom"
			round="16"
			closeable
			title="选择物流公司"
			:zIndex="9999"
			:safeAreaInsetBottom="true"
			@close="showSelect = false"
		>
			<div class="select-popup">
				<!-- 列表容器 - 确保内容可滚动 -->
				<scroll-view scroll-y="true" class="option-list" :style="{ height: scrollViewHeight }">
					<!-- 加载状态 -->
					<div v-if="loading" class="loading-container">
						<u-loading-icon text="加载中"></u-loading-icon>
					</div>

					<!-- 空状态 -->
					<div v-else-if="expressList.length === 0" class="empty-container">
						<u-empty mode="search" text="暂无物流公司数据"></u-empty>
					</div>

					<!-- 公司列表 - 添加touch事件确保移动端兼容 -->
					<div
						v-for="express in expressList"
						:key="express.id"
						class="option-item"
						:class="{ selected: form.logisticsId === express.id }"
						@touchstart="touchStart(express)"
						@touchend="touchEnd(express)"
						@click="selectLogistics(express)"
					>
						<div class="option-content">
							<div class="option-name">
								<span class="company-name">{{ express.name }}</span>
							</div>
							<div class="option-check" v-if="form.logisticsId === express.id">
								<u-icon name="checkmark" color="#2979ff" size="20"></u-icon>
							</div>
						</div>
					</div>
				</scroll-view>
			</div>
		</u-popup>

		<div class="form-actions">
			<u-button shape="circle" plain @click="$emit('cancel')" customStyle="width: 45%; height: 48px; border: 1px solid #dcdfe6;"> 取消 </u-button>
			<u-button type="primary" shape="circle" @click="handleSubmit" customStyle="width: 45%; height: 48px;"> 确定 </u-button>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { getSimpleDeliveryExpressList } from '@/api/mall/trade/delivery/express';

const props = defineProps<{
	orderId: number | null;
}>();

const emit = defineEmits(['submit', 'cancel']);

// 表单数据
const form = reactive({
	id: props.orderId || 0,
	deliveryType: 1, // 1=快递物流, 0=无需发货
	logisticsId: null as number | null,
	logisticsNo: '',
});

// 物流公司选择状态
const showSelect = ref(false);
const selectedLogisticsName = ref('');
const expressList = ref([]);
const loading = ref(false);
const logisticsError = ref(''); // 错误提示
let touchTimer: any = null; // 触摸计时器

// 订单号显示
const orderNo = computed(() => `DD2023060${props.orderId}`);

// 计算滚动视图高度
const scrollViewHeight = computed(() => {
	const itemCount = expressList.value.length;
	const minHeight = 300; // 最小高度
	const maxHeight = 600; // 最大高度
	const itemHeight = 54; // 每个选项高度
	const headerHeight = 60; // 弹窗头部高度

	// 计算内容高度
	const contentHeight = headerHeight + itemCount * itemHeight;

	// 确保高度在最小和最大之间
	if (contentHeight < minHeight) return `${minHeight}px`;
	if (contentHeight > maxHeight) return `${maxHeight}px`;
	return `${contentHeight}px`;
});

// 获取物流公司列表
const fetchExpressList = async () => {
	try {
		loading.value = true;
		logisticsError.value = '';
		const response = await getSimpleDeliveryExpressList();

		// 调试打印接口响应
		console.log('物流公司接口响应:', response);

		// 确保接口返回了data数组
		if (response && response.data && Array.isArray(response.data)) {
			expressList.value = response.data;

			// 如果只有一项物流公司，自动选中
			if (response.data.length === 1) {
				const express = response.data[0];
				form.logisticsId = express.id;
				selectedLogisticsName.value = express.name;
			}
		} else {
			logisticsError.value = '返回数据格式不正确';
			console.error('物流公司数据格式错误:', response);
		}
	} catch (error) {
		console.error('获取物流公司列表失败:', error);
		logisticsError.value = '加载物流公司失败';
		uni.showToast({
			title: '获取物流公司列表失败',
			icon: 'error',
		});
	} finally {
		loading.value = false;
	}
};

// 触摸开始事件（解决移动端点击延迟问题）
const touchStart = (express: any) => {
	touchTimer = setTimeout(() => {
		console.log('触摸开始');
		// 如果需要长按效果可以在这里添加
	}, 500);
};

// 触摸结束事件
const touchEnd = (express: any) => {
	clearTimeout(touchTimer);
};

// 选择物流公司
const selectLogistics = (express: any) => {
	console.log('选择物流公司:', express);

	// 确保有有效的id和name
	if (express && express.id && express.name) {
		form.logisticsId = express.id;
		selectedLogisticsName.value = express.name;
		showSelect.value = false;
	} else {
		console.error('无效的物流公司数据:', express);
		uni.showToast({
			title: '选择物流公司失败',
			icon: 'none',
		});
	}
};

// 当显示选择框时加载数据
watch(showSelect, (val) => {
	if (val) {
		if (expressList.value.length === 0) {
			fetchExpressList();
		} else {
			console.log('已有物流公司数据:', expressList.value.length);
		}
	}
});

// 提交表单
const handleSubmit = async () => {
	// 准备提交数据
	const submitData = {
		id: form.id,
		deliveryType: form.deliveryType,
		logisticsId: form.deliveryType === 0 ? 0 : form.logisticsId,
		logisticsNo: form.deliveryType === 0 ? '' : form.logisticsNo,
	};

	// 验证快递物流模式下的输入
	if (form.deliveryType === 1) {
		if (!submitData.logisticsId || !submitData.logisticsNo) {
			logisticsError.value = '请填写完整的物流信息';
			uni.showToast({
				title: '请填写完整的物流信息',
				icon: 'none',
			});
			return;
		}
	}

	// 提交数据
	emit('submit', submitData);
};

// 组件挂载时调试信息
onMounted(() => {
	console.log('发货组件已挂载，orderId:', props.orderId);
});
</script>

<style lang="scss" scoped>
.delivery-form-container {
	padding: 24px;
	background: #fff;
	border-radius: 16px;
	box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
	background-color: #ffffff;
	color: #333333;
	background: linear-gradient(135deg, #fff9c4 0%, #ffffff 100%);

	.form-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;
		padding-bottom: 16px;
		border-bottom: 1px solid #f0f0f0;
		position: relative;

		.title-box {
			.title {
				font-size: 20px;
				font-weight: bold;
				color: #333;
				margin-bottom: 6px;
				position: relative;
				display: inline-block;

				&::after {
					content: '';
					position: absolute;
					bottom: -5px;
					left: 0;
					width: 100%;
					height: 2px;
					background: linear-gradient(to right, #2979ff, #2b85e4);
					border-radius: 1px;
				}
			}

			.order-no {
				font-size: 14px;
				color: #666666;
				margin-top: 4px;
			}
		}

		.close-icon {
			background: #f5f5f5;
			padding: 8px;
			border-radius: 50%;
			cursor: pointer;
			transition: all 0.3s;

			&:active {
				background-color: #e0e0e0;
				transform: rotate(90deg);
			}
		}
	}

	.form-content {
		padding: 0 8px;

		.error-tip {
			color: #e54d42;
			font-size: 12px;
			margin-top: 8px;
		}

		:deep(.u-form-item) {
			margin-bottom: 24px;

			.u-form-item__body__left__content__label {
				font-weight: bold;
				font-size: 15px;
				color: #333;
				margin-bottom: 10px;
				display: block;
			}
		}

		.delivery-type-container {
			display: flex;
			gap: 16px;
			margin-top: 8px;

			.delivery-type-option {
				flex: 1;
				display: flex;
				align-items: center;
				padding: 14px;
				border-radius: 12px;
				border: 1px solid #e0e0e0;
				cursor: pointer;
				transition: all 0.3s;
				background: #fafafa;
				min-height: 60px;
				box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);

				&.active {
					border-color: #2979ff;
					background-color: #ecf5ff;
					box-shadow: 0 3px 6px rgba(41, 121, 255, 0.15);
				}

				.option-icon {
					margin-right: 10px;
					display: flex;
					align-items: center;
					justify-content: center;
					width: 24px;
					height: 24px;
				}

				.option-text {
					font-size: 15px;
					color: #333;
					font-weight: 500;
					flex: 1;
				}
			}
		}

		.select-wrapper {
			position: relative;
			cursor: pointer;
			margin-top: 8px;
			z-index: 1;

			:deep(.u-input) {
				background: #fafafa;
				border-radius: 8px;
				padding: 12px 16px;
				border: 1px solid #e0e0e0;
				transition: all 0.2s;

				&:hover {
					border-color: #2979ff;
					background: #f0f7ff;
				}
			}
		}
	}

	.form-actions {
		display: flex;
		justify-content: space-between;
		margin-top: 20px;
		padding-top: 20px;
		border-top: 1px solid #f0f0f0;
	}
}

.select-popup {
	background: #fff;
	display: flex;
	flex-direction: column;
	border-top-left-radius: 16px;
	border-top-right-radius: 16px;
	overflow: hidden;
	max-height: 80vh;

	.option-list {
		padding: 16px;
		box-sizing: border-box;
		overflow-y: auto;
		-webkit-overflow-scrolling: touch;
		/* 优化移动端滚动 */
		overscroll-behavior: contain;
		/* 防止滚动穿透 */

		.loading-container {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 200px;
		}

		.empty-container {
			padding: 40px 0;
		}

		.option-item {
			padding: 18px 16px;
			border-radius: 10px;
			border: 1px solid #f0f0f0;
			margin-bottom: 12px;
			cursor: pointer;
			transition: all 0.2s;
			background: #fafafa;
			position: relative;
			box-shadow: 0 2px 4px rgba(0, 0, 0, 0.03);

			/* 点击效果 */
			&:active {
				transform: scale(0.98);
				box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
				background: #f5f5f5;
			}

			&.selected {
				border-color: #2979ff;
				background-color: #ecf5ff;
				box-shadow: 0 3px 6px rgba(41, 121, 255, 0.12);
			}

			.option-content {
				display: flex;
				align-items: center;
				justify-content: space-between;
			}

			.option-name {
				.company-name {
					font-size: 16px;
					color: #333;
					font-weight: 500;
				}
			}

			.option-check {
				display: flex;
				align-items: center;
			}
		}
	}
}
</style>
